package website.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import website.constants.Code;
import website.domain.ResModel;
import website.domain.UserHolder;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {


    //目标资源执行前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (UserHolder.getUser()==null){
            return unLoginHandler(response);
        }
        return true;
    }

    //请求完成后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }

    /**
     * 未登录处理
     * @param response
     * @throws Exception
     */
    private boolean unLoginHandler(HttpServletResponse response) throws Exception{
        ObjectMapper mapper = new ObjectMapper();
        String s = mapper.writeValueAsString(ResModel.error(Code.NOT_LOGGED_IN));
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(s);
        return false;
    }
}
